//
//  WLAlertView.m
//
//  Created by zp on 16/8/5.
//  Copyright © 2016年 All rights reserved.
//

#import "WLAlertView.h"
#import "AppDelegate.h"
#import "UIView+DDAddition.h"
//#import "NT_MeWalletAuditWaitView.h"

#define TITLE_FONT_SIZE 14
#define MESSAGE_FONT_SIZE 12
#define BUTTON_FONT_SIZE 16
#define MARGIN_TOP 20
#define MARGIN_LEFT_LARGE 30
#define MARGIN_LEFT_SMALL 15
#define MARGIN_RIGHT_LARGE 30
#define MARGIN_RIGHT_SMALL 15
#define SPACE_LARGE 20
#define SPACE_SMALL 5
#define MESSAGE_LINE_SPACE 5

#define kLGAlertViewWidthStyleAlert                   (320.f - 20*2)
#define KWLRGBA(r, g, b,a) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:(a)]

#define kWLTextColor_85 KWLRGBA(85,85,85,1)
#define kWLTextColor_173 KWLRGBA(173,173,173,1)
#define kWLTextColor_230 KWLRGBA(230,230,230,1)

#define KWLSCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)
#define KWLSCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
@interface WLAlertView ()

@property (nonatomic , strong) UIView   *contentView;
@property (nonatomic , strong) NSString *title;
@property (nonatomic , strong) NSString *message;

@property (nonatomic , strong) UIView  *backgroundView;
@property (nonatomic , strong) UILabel *titleLabel;
@property (nonatomic , strong) UILabel *messageLabel;

@property (nonatomic , strong) NSMutableArray *buttonArray;
@property (nonatomic , strong) NSMutableArray *buttonTitleArray;

@property (nonatomic , assign) BOOL isShowControlsButton; //是否显示控件button
@property (nonatomic , assign) WLShowAnimationStyle animationStyle;//动画样式

@property (assign, nonatomic) CGFloat keyboardHeight;

@end

CGFloat contentViewWidth;
CGFloat contentViewHeight;

@implementation WLAlertView

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
    if (self.shouldHideTouchingBackground) {
        [self hide];
    }
}

#pragma mark 初始化
//默认样式（类似系统alert） 初始化
- (instancetype) initWithTitle:(NSString *)title
                          message:(NSString *)message
                         delegate:(id<WLAlertViewDelegate>)delegate
                     buttonTitles:(NSString *)buttonTitles, ... {
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds] ) {
        _title = title;
        _message = message;
        _delegate = delegate;
        _buttonArray = [NSMutableArray array];
        _buttonTitleArray = [NSMutableArray array];
        
        va_list args;
        va_start(args, buttonTitles);
        if (buttonTitles)
        {
            [_buttonTitleArray addObject:buttonTitles];
            while (1)
            {
                NSString *  otherButtonTitle = va_arg(args, NSString *);
                if(otherButtonTitle == nil) {
                    break;
                } else {
                    [_buttonTitleArray addObject:otherButtonTitle];
                }
            }
        }
        va_end(args);
        
        self.backgroundColor = [UIColor clearColor];
        
        _backgroundView = [[UIView alloc] initWithFrame:self.frame];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [self addSubview:_backgroundView];
        [self initContentView];

    }
    return self;
}


//自定义样式（自定义View）
- (instancetype) initWithCustomView:(UIView *)customView
               isShowControlsButton:(BOOL)isShow
                              delegate:(id<WLAlertViewDelegate>)delegate
                          buttonTitles:(NSString *)buttonTitles, ... {
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds] ) {
        _contentView = customView;
        _isShowControlsButton = isShow;
        _delegate = delegate;
        _buttonArray = [NSMutableArray array];
        _buttonTitleArray = [NSMutableArray array];
        
        va_list args;
        va_start(args, buttonTitles);
        if (buttonTitles)
        {
            [_buttonTitleArray addObject:buttonTitles];
            while (1)
            {
                NSString *  otherButtonTitle = va_arg(args, NSString *);
                if(otherButtonTitle == nil) {
                    break;
                } else {
                    [_buttonTitleArray addObject:otherButtonTitle];
                }
            }
        }
        va_end(args);
        
        self.backgroundColor = [UIColor clearColor];
        
        _backgroundView = [[UIView alloc] initWithFrame:self.frame];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [self addSubview:_backgroundView];
        [self initContentView];
    }
    return self;
}


// Init the content of content view
- (void)initContentView {
    if (_contentView) {
        if (_isShowControlsButton == YES) {
            contentViewWidth = _contentView.frame.size.width;
            contentViewHeight = _contentView.frame.size.height;
            [self initAllButtons];
            _contentView.frame = CGRectMake(0, 0, contentViewWidth, contentViewHeight);
        }
        _contentView.center = self.center;
        _contentView.layer.cornerRadius = 5.0;
        _contentView.layer.masksToBounds = YES;
        [self addSubview:_contentView];
    
//        if ([_contentView isKindOfClass:[NT_MeWalletAuditWaitView class]]) {
//            
//            CGFloat top = (iPhoneX) ? (184 + 24) : 184;
//            [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//                
//                make.top.mas_equalTo(top);
//                make.left.mas_equalTo(52);
//                make.right.mas_equalTo(-52);
//                
//            }];
//        }
        
    }else {
        contentViewWidth = kLGAlertViewWidthStyleAlert;
        contentViewHeight = MARGIN_TOP;
    
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.cornerRadius = 5.0;
        _contentView.layer.masksToBounds = YES;
        
        [self initTitleAndIcon];
        [self initMessage];
        [self initAllButtons];
        
        _contentView.frame = CGRectMake(0, 0, contentViewWidth, contentViewHeight);
        _contentView.center = self.center;
        [self addSubview:_contentView];
    }
}

// 添加标题
- (void)initTitleAndIcon {

    CGSize titleSize = [self getTitleSize];
    if (_title != nil && ![_title isEqualToString:@""]) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = _title;
        _titleLabel.textColor = kWLTextColor_85;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:TITLE_FONT_SIZE];
        _titleLabel.numberOfLines = 0;
        _titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _titleLabel.frame = CGRectMake(SPACE_SMALL, 1, titleSize.width, titleSize.height);
        _titleLabel.frame = CGRectMake(0, MARGIN_TOP, SPACE_SMALL + titleSize.width, titleSize.height);
        _titleLabel.center = CGPointMake(contentViewWidth / 2, MARGIN_TOP + _titleLabel.frame.size.height / 2);
        [_contentView addSubview:_titleLabel];
        contentViewHeight += _titleLabel.frame.size.height;
    }
}

// 添加内容
- (void)initMessage {
    if (_message != nil) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.text = _message;
        _messageLabel.textColor = kWLTextColor_173;
        _messageLabel.numberOfLines = 0;
        _messageLabel.font = [UIFont systemFontOfSize:MESSAGE_FONT_SIZE];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineSpacing = MESSAGE_LINE_SPACE;
        NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle};
        _messageLabel.attributedText = [[NSAttributedString alloc]initWithString:_message attributes:attributes];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        
        CGSize messageSize = [self getMessageSize];
        _messageLabel.frame = CGRectMake(MARGIN_LEFT_LARGE, _titleLabel.frame.origin.y + _titleLabel.frame.size.height + SPACE_LARGE, MAX(contentViewWidth - MARGIN_LEFT_LARGE - MARGIN_RIGHT_LARGE, messageSize.width), messageSize.height);
        [_contentView addSubview:_messageLabel];
        contentViewHeight += SPACE_LARGE + _messageLabel.frame.size.height;
    }
}

// 添加按钮
- (void)initAllButtons {
    if (_buttonTitleArray.count > 0) {
        UIView *horizonSperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, contentViewHeight + SPACE_LARGE, contentViewWidth, 1)];
        horizonSperatorView.backgroundColor = kWLTextColor_230;
        [_contentView addSubview:horizonSperatorView];
        
        if (_buttonTitleArray.count > 2) {
            contentViewHeight += SPACE_LARGE + _buttonTitleArray.count*44 + 1;
            if (contentViewHeight >= KWLSCREEN_HEIGHT) {
                contentViewHeight = KWLSCREEN_HEIGHT;
            }
            for (NSString *buttonTitle in _buttonTitleArray) {
                NSInteger index = [_buttonTitleArray indexOfObject:buttonTitle];
                UIButton *button = [self setupButtonWithTitle:buttonTitle];
                button.frame = CGRectMake(0, horizonSperatorView.frame.origin.y + horizonSperatorView.frame.size.height + index * 44, contentViewWidth, 44);
                [_buttonArray addObject:button];
                [_contentView addSubview:button];
                
                if (index < _buttonTitleArray.count - 1) {
                    UIView *verticalSeperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, button.bottom - 1, contentViewWidth, 1)];
                    verticalSeperatorView.backgroundColor = kWLTextColor_230;
                    [_contentView addSubview:verticalSeperatorView];
                }
            }
        }else {
            contentViewHeight += SPACE_LARGE + 45;
            CGFloat buttonWidth = contentViewWidth / _buttonTitleArray.count;
            for (NSString *buttonTitle in _buttonTitleArray) {
                NSInteger index = [_buttonTitleArray indexOfObject:buttonTitle];
                UIButton *button = [self setupButtonWithTitle:buttonTitle];
                button.frame = CGRectMake(index * buttonWidth, horizonSperatorView.frame.origin.y + horizonSperatorView.frame.size.height, buttonWidth, 44);
                [_buttonArray addObject:button];
                [_contentView addSubview:button];
                
                if (index < _buttonTitleArray.count - 1) {
                    UIView *verticalSeperatorView = [[UIView alloc] initWithFrame:CGRectMake(button.right - 1, button.frame.origin.y, 1, button.frame.size.height)];
                    verticalSeperatorView.backgroundColor = kWLTextColor_230;
                    [_contentView addSubview:verticalSeperatorView];
                }
            }
        }
    }
}

-(UIButton *)setupButtonWithTitle:(NSString *)title {
    UIButton *button = [[UIButton alloc]init];
    button.backgroundColor = [UIColor whiteColor];
    button.titleLabel.font = [UIFont systemFontOfSize:BUTTON_FONT_SIZE];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:kWLTextColor_85 forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonWithPressed:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

// 计算 size of title
- (CGSize)getTitleSize {
    UIFont *font = [UIFont systemFontOfSize:TITLE_FONT_SIZE];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize size = [_title boundingRectWithSize:CGSizeMake(contentViewWidth - (MARGIN_LEFT_SMALL + MARGIN_RIGHT_SMALL + SPACE_SMALL), 2000)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attributes context:nil].size;
    
    size.width = ceil(size.width);
    size.height = ceil(size.height);
    
    return size;
}

// 计算 size of message
- (CGSize)getMessageSize {
    UIFont *font = [UIFont systemFontOfSize:MESSAGE_FONT_SIZE];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = MESSAGE_LINE_SPACE;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize size = [_message boundingRectWithSize:CGSizeMake(contentViewWidth - (MARGIN_LEFT_LARGE + MARGIN_RIGHT_LARGE), 2000)
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:attributes context:nil].size;
    
    size.width = ceil(size.width);
    size.height = ceil(size.height);
    
    return size;
}

- (void)buttonWithPressed:(UIButton *)button {
    if (_delegate && [_delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)]) {
        NSInteger index = [_buttonTitleArray indexOfObject:button.titleLabel.text];
        if (index == 0) {
            [self hide];
        }
        [_delegate alertView:self clickedButtonAtIndex:index];
    }
//    [self hide];
}


#pragma mark 显示 隐藏
//显示
- (void)show:(WLShowAnimationStyle)animationStyle{
    _animationStyle = animationStyle;
//    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
//    UIWindow *window = [AppDelegate sharedAppDelegate].window;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    NSArray *windowViews = [window subviews];
    if(windowViews && [windowViews count] > 0){
//        UIView *subView = [windowViews objectAtIndex:[windowViews count]-1];
//        for(UIView *aSubView in subView.subviews)
//        {
//            [aSubView.layer removeAllAnimations];
//        }
        [window addSubview:self];
        [self showBackground];
        [self showAlertAnimation];
    }
}

//隐藏
- (void)hide{
    _contentView.hidden = YES;
    [self hideAlertAnimation];
    [self removeFromSuperview];
}


#pragma mark 动画
- (void)showBackground
{
    _backgroundView.alpha = 0;
    [UIView beginAnimations:@"fadeIn" context:nil];
    [UIView setAnimationDuration:0.35];
    _backgroundView.alpha = 0.6;
    [UIView commitAnimations];
}

-(void)showAlertAnimation
{
    if (_animationStyle == WLAnimationDefault) {
        [self addObservers];
        CAKeyframeAnimation * animation;
        animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        animation.duration = 0.30;
        animation.removedOnCompletion = YES;
        animation.fillMode = kCAFillModeForwards;
        NSMutableArray *values = [NSMutableArray array];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
        animation.values = values;
        [_contentView.layer addAnimation:animation forKey:nil];
    }
}

- (void)hideAlertAnimation {
    [self removeObservers];
    [UIView beginAnimations:@"fadeIn" context:nil];
    [UIView setAnimationDuration:0.35];
    _backgroundView.alpha = 0.0;
    [UIView commitAnimations];
}



#pragma mark 属性设置
- (void)setTitleColor:(UIColor *)color fontSize:(CGFloat)size {
    if (color != nil) {
        _titleLabel.textColor = color;
    }
    
    if (size > 0) {
        _titleLabel.font = [UIFont systemFontOfSize:size];
    }
}


- (void)setMessageColor:(UIColor *)color fontSize:(CGFloat)size {
    if (color != nil) {
        _messageLabel.textColor = color;
    }
    
    if (size > 0) {
        _messageLabel.font = [UIFont systemFontOfSize:size];
    }
}


- (void)setButtonTitleColor:(UIColor *)color fontSize:(CGFloat)size atIndex:(NSInteger)index {
    UIButton *button = _buttonArray[index];
    if (color != nil) {
        [button setTitleColor:color forState:UIControlStateNormal];
    }
    
    if (size > 0) {
        button.titleLabel.font = [UIFont systemFontOfSize:size];
    }
}

#pragma mark - Observers
- (void)addObservers
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardVisibleChanged:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardVisibleChanged:) name:UIKeyboardDidHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)removeObservers
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}


#pragma mark - Keyboard notifications

- (void)keyboardVisibleChanged:(NSNotification *)notification
{
    [WLAlertView keyboardAnimateWithNotificationUserInfo:notification.userInfo
                                              animations:^(CGFloat keyboardHeight)
     {
         if ([notification.name isEqualToString:UIKeyboardWillShowNotification]){
             _keyboardHeight = keyboardHeight;
             _contentView.top = self.centerY - _keyboardHeight;
         }else{
             _keyboardHeight = 0.f;
             _contentView.center = self.center;
         }
     }];
}

- (void)keyboardFrameChanged:(NSNotification *)notification
{
    if ([notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] == 0.f)
        _keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
}


+ (void)keyboardAnimateWithNotificationUserInfo:(NSDictionary *)notificationUserInfo animations:(void(^)(CGFloat keyboardHeight))animations
{
    CGFloat keyboardHeight = (notificationUserInfo[UIKeyboardFrameEndUserInfoKey] ? [notificationUserInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height : 0.f);
    
    if (!keyboardHeight) return;
    
    NSTimeInterval animationDuration = [notificationUserInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int animationCurve = [notificationUserInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    if (animations) animations(keyboardHeight);
    
    [UIView commitAnimations];
}


@end
